#include "MQTTManager.h"
#include <ArduinoJson.h>
#include "../../application/App.h"

// 订阅的主题
String prefix = "/" + String(PRODUCT_ID) + "/" + String(DEVICE_NUM);
String sInfoTopic = prefix + "/info/get";
String sOtaTopic = prefix + "/ota/get";
String sNtpTopic = prefix + "/ntp/get";
String sPropertyTopic = prefix + "/property/get";
String sFunctionTopic = prefix + "/function/get";
String sPropertyOnline = prefix + "/property-online/get";
String sFunctionOnline = prefix + "/function-online/get";
String sMonitorTopic = prefix + "/monitor/get";
// 发布的主题
String pInfoTopic = prefix + "/info/post";
String pNtpTopic = prefix + "/ntp/post";
String pPropertyTopic = prefix + "/property/post";
String pFunctionTopic = prefix + "/function/post";
String pMonitorTopic = prefix + "/monitor/post";
String pEventTopic = prefix + "/event/post";

void callback(char* topic, uint8_t* payload, unsigned int length) {
    Serial.print("Message arrived [");
    Serial.print(topic);
    Serial.print("] ");
    for (unsigned int i = 0; i < length; i++) {
        Serial.print((char)payload[i]);
    }
    Serial.println();
}

void MQTTManager::connect() {
    _mqttClient.setClient(_wifiClient);
    _mqttClient.setServer(MQTT_HOST, MQTT_PORT);
    _mqttClient.setCallback(callback);
    _mqttClient.setBufferSize(1024);
    _mqttClient.setKeepAlive(10);
    // 设备mqtt客户端Id
    String clientId = "S&" + String(DEVICE_NUM) + "&" + String(PRODUCT_ID) +
                      "&" + String(USER_ID);
    Serial.println("[MQTT] clientId:" + clientId);
    bool connectResult =
        _mqttClient.connect(clientId.c_str(), MQTT_USERNAME, MQTT_PASSWORD);
    if (connectResult) {
        Serial.println("[MQTT] Connected");
        // 订阅(OTA、NTP、属性、功能、实时监测、信息)
        _mqttClient.subscribe(sInfoTopic.c_str(), 1);
        _mqttClient.subscribe(sOtaTopic.c_str(), 1);
        _mqttClient.subscribe(sNtpTopic.c_str(), 1);
        _mqttClient.subscribe(sPropertyTopic.c_str(), 1);
        _mqttClient.subscribe(sFunctionTopic.c_str(), 1);
        _mqttClient.subscribe(sPropertyOnline.c_str(), 1);
        _mqttClient.subscribe(sFunctionOnline.c_str(), 1);
        _mqttClient.subscribe(sMonitorTopic.c_str(), 1);
        Serial.println("[MQTT] Subscribe Topic: " + sInfoTopic);
        Serial.println("[MQTT] Subscribe Topic: " + sOtaTopic);
        Serial.println("[MQTT] Subscribe Topic: " + sNtpTopic);
        Serial.println("[MQTT] Subscribe Topic: " + sPropertyTopic);
        Serial.println("[MQTT] Subscribe Topic: " + sFunctionTopic);
        Serial.println("[MQTT] Subscribe Topic: " + sPropertyOnline);
        Serial.println("[MQTT] Subscribe Topic: " + sFunctionOnline);
        Serial.println("[MQTT] Subscribe Topic: " + sMonitorTopic);
        Serial.println("[MQTT] Subscribe Sueccess");
        // 发布设备信息
        publishInfo();
    } else {
        Serial.println("[MQTT] Connection failed");
        Serial.print(_mqttClient.state());
    }
}

void MQTTManager::loop() {
    _mqttClient.loop();
}

void MQTTManager::publishInfo() {
    StaticJsonDocument<256> doc;
    doc["rssi"] = WiFi.RSSI();
    doc["firmwareVersion"] = 1055;
    doc["status"] = 3;  // （1-未激活，2-禁用，3-在线，4-离线）
    doc["userId"] = (String)USER_ID;
    doc["longitude"] = "104.70247633930025";  // 经度 可选
    doc["latitude"] = "31.49413191464186";    // 纬度 可选
    // 设备摘要,可选（自定义配置信息,不限数量）
    JsonObject summary = doc.createNestedObject("summary");
    summary["name"] = "ESP32-001";
    summary["author"] = "FRSF";
    summary["create"] = "2025-04-09";
    Serial.println("[MQTT] 发布设备信息");
    serializeJson(doc, Serial);
    String output;
    serializeJson(doc, output);
    _mqttClient.publish(pInfoTopic.c_str(), output.c_str());
}

void MQTTManager::publishProperty(float temperature, float humidity) {
    StaticJsonDocument<1024> doc;
    // 将 doc 转换为 JSON 数组
    JsonArray properties = doc.to<JsonArray>();

    // 添加第一个 JSON 对象
    JsonObject tempObj = properties.createNestedObject();
    tempObj["id"] = "temperature";
    tempObj["value"] = temperature;

    // 添加第二个 JSON 对象
    JsonObject humiObj = properties.createNestedObject();
    humiObj["id"] = "humidity";
    humiObj["value"] = humidity;

    // 序列化 JSON 文档到字符串
    String output;
    serializeJson(doc, output);

    // 打印 JSON 字符串到串口（调试用）
    Serial.println("[MQTT] 发布属性信息");
    Serial.println(output);

    // 发布到 MQTT 主题
    _mqttClient.publish(pPropertyTopic.c_str(), output.c_str());
}